package com.jzo2o.orders.manager.strategy;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.orders.base.enums.OrderPayStatusEnum;
import com.jzo2o.orders.base.enums.OrderStatusEnum;
import com.jzo2o.orders.base.model.domain.Orders;
import com.jzo2o.orders.manager.model.dto.OrderCancelDTO;
import com.jzo2o.orders.manager.service.IOrdersManagerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;

@Component
@Slf4j
public class OrderCancelStrategyManager {

    Map<String, OrderCancelStrategy> cancelStrategyBeans;
    @Autowired
    private IOrdersManagerService ordersManagerService;

    @Autowired
    private CouponApi couponApi;


    @PostConstruct
    public void init(){
        //初始化拿到该策略下的所有bean
         cancelStrategyBeans = SpringUtil.getBeansOfType(OrderCancelStrategy.class);
    }


    public void cancel(OrderCancelDTO orderCancelDTO)
    {
        //根据参数的订单id查询订单，检查订单状态判断使用哪一个策略类
        Orders orders = ordersManagerService.getById(orderCancelDTO.getId());
        if(ObjectUtil.isNull(orders)){
            throw new ForbiddenOperationException("订单不存在");
        }
        BeanUtil.copyProperties(orders,orderCancelDTO);

        //退回逻辑
        //添加退回优惠券的逻辑
        if (orders.getDiscountAmount().compareTo(BigDecimal.ZERO) > 0){
            CouponUseBackReqDTO couponUseBackReqDTO = new CouponUseBackReqDTO();
            couponUseBackReqDTO.setOrdersId(orders.getId());//订单id
            couponUseBackReqDTO.setUserId(orders.getUserId());//用户id
            couponApi.useBack(couponUseBackReqDTO);
        }


        //拼接策略类的key：用户类型：订单状态
        String key = orderCancelDTO.getCurrentUserType() + ":" + OrderStatusEnum.codeOf(orders.getOrdersStatus());
        OrderCancelStrategy orderCancelStrategy = cancelStrategyBeans.get(key);
        if(ObjectUtil.isNull(orderCancelStrategy)){
            throw new ForbiddenOperationException("该策略不存在，执行失败");
        }
        orderCancelStrategy.cancel(orderCancelDTO);
    }
}
